﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Coolzon.UI.Core
{
    /// <summary>
    /// </summary>
    public class PartLibraryManager
    {

        public static Dictionary<string, Type> PartTypeDict = new Dictionary<string, Type>();
        public static Dictionary<Type, Type> ConverterTypeDict = new Dictionary<Type, Type>();
        private static object s_lock = new object();
        /// <summary>
        /// 初始化
        /// </summary>
        public static void Initiate(List<Coolzon.Web.Models.Library> libraries)
        {
            //ResolveEventHandler handler = (ResolveEventHandler)GetEventValue(AppDomain.CurrentDomain, "AssemblyResolve");
            AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
            {
                try
                {
                    string filepath = string.Format("{0}.dll", System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, args.Name));
                    if (System.IO.File.Exists(filepath))
                    {
                        return Assembly.LoadFile(filepath);
                    }
                }
                catch
                {

                }

                try
                {
                    string filepath = null;
                    if (Environment.Is64BitProcess)
                    {
                        filepath = string.Format("{0}-64.dll", System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, args.Name));
                    }
                    else
                    {
                        filepath = string.Format("{0}-32.dll", System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, args.Name));
                    }
                    if (System.IO.File.Exists(filepath))
                    {
                        return Assembly.LoadFile(filepath);
                    }
                }
                catch
                {

                }
                if (args.RequestingAssembly == null)
                {
                    return null;
                }

                string libraryName = args.RequestingAssembly.GetName().Name;
                string dependencyName = new AssemblyName(args.Name).Name;
                foreach (var library in libraries)
                {
                    if (string.Equals(libraryName, library.Name, StringComparison.CurrentCultureIgnoreCase))
                    {
                        foreach (var dependency in library.Dependencies)
                        {
                            if (string.Equals(dependencyName, dependency.Name, StringComparison.CurrentCultureIgnoreCase))
                            {
                                string filepath = System.IO.Path.Combine(library.AbsoluteDirectory, dependency.File);
                                return Assembly.LoadFile(filepath);
                            }
                        }
                    }
                }
                return null;
            };

            new CorePartLibrary().Install();

            Assembly commonLibraryAssembly = Assembly.Load("Coolzon.UI.Common");
            (commonLibraryAssembly.CreateInstance("Coolzon.UI.Common.CommonPartLibrary") as PartLibrary).Install();

            Assembly chartLibraryAssembly = Assembly.Load("Coolzon.UI.Charts");
            (chartLibraryAssembly.CreateInstance("Coolzon.UI.Charts.ChartLibrary") as PartLibrary).Install();

            //// 加载组件库的程序集
            //foreach (var library in libraries)
            //{
            //    string libraryFilePath = System.IO.Path.Combine(library.AbsoluteDirectory, library.File);
            //    Assembly libraryAssembly = LoadAssembly(libraryFilePath);
            //    PartLibrary instance = GetLibraryInstance(libraryAssembly);
            //    if (instance != null)
            //    {
            //        instance.Install();
            //    }
            //}
        }

        private static Assembly LoadAssembly(string filepath)
        {
            return Assembly.LoadFile(filepath);// Assembly.Load(System.IO.File.ReadAllBytes(filepath));
        }

        private static PartLibrary GetLibraryInstance(Assembly libraryAssembly)
        {
            Type[] types = libraryAssembly.GetTypes();
            foreach (var type in types)
            {
                if(type.IsSubclassOf(typeof(PartLibrary)))
                {
                    return (PartLibrary)libraryAssembly.CreateInstance(type.FullName);
                }
            }
            return null;
        }
    }
}
